package com.javaweb.service.Impl;


import com.javaweb.aop.GranularType;
import com.javaweb.aop.TimeMeasure;
import com.javaweb.common.StringUtils;
import com.javaweb.dao.UserDao;
import com.javaweb.model.User;
import com.javaweb.service.UserService;
import com.javaweb.service.dto.PageResult;
import com.javaweb.service.dto.UserConditionDto;
import com.javaweb.service.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/9/23 12:36
 */
@TimeMeasure(granular = GranularType.MIL_SECOND)
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao ;
    @Override
    public User login(String username, String password) {
       if (username==null){
           throw new IllegalArgumentException("username is null");
       }
       if (password==null){
           throw new IllegalArgumentException("password is null");
       }
       User user=userDao.selectOne(username, password) ;
        // 如果没有找到用户，抛出异常
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
       return user;
    }

    @Override
    public List<User> queryByName(String username) {
        if (username==null){
            throw new IllegalArgumentException("username is null");
        }
        List<User> users=userDao.selectByName(username) ;
        return users;
    }

    @Override
    public int register(User user) {
        if (user==null){
            throw new IllegalArgumentException("user is null");
        }
        int ret=userDao.insert(user);
        return ret>0?1:0;
    }

    @Override
    public PageResult queryUsers(User userCondition, Integer pageNum, Integer pageSize) {
        // 检查页码和每页大小是否有效
        if (pageNum == null || pageNum <= 0) {
            throw new IllegalArgumentException("pageNum must be greater than 0");
        }
        if (pageSize == null || pageSize <= 0) {
            throw new IllegalArgumentException("pageSize must be greater than 0");
        }

        String username = userCondition.getName();
        List<User> allUsers = userDao.selectByName(username); // 获取所有符合条件的用户

        // 手动实现分页
        int total = allUsers.size(); // 总记录数
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        List<User> pagedUsers = allUsers.subList(fromIndex, toIndex); // 获取当前页的数据

        // 创建 PageResult 对象并设置数据
        PageResult<User> pageResult = new PageResult<>();
        pageResult.setData(pagedUsers);
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotal(total);

        return pageResult; // 返回分页结果
    }


    @Override
    public void addAssignRole(String userId, List<String> roleIds) {
        // 检查用户 ID 是否有效
        if (userId == null) {
            throw new IllegalArgumentException("userId is null ");
        }
        // 检查角色 ID 列表是否有效
        if (roleIds == null ) {
            throw new IllegalArgumentException("roleIds is null ");
        }
        Integer userid=Integer.parseInt(userId);
        for (String roleId : roleIds) {
            Integer roleid=Integer.parseInt(roleId);
            userDao.insertUserRole(userid,roleid);//调用了userDao层中的insertUserRole()方法
        }
    }

    @Override
    public List<Integer> getRoleIdsByUserId(String userId) {
        // 检查用户 ID 是否有效
        if (userId == null) {
            throw new IllegalArgumentException("userId is null");
        }
        return userDao.getRoleIdsByUserId(Integer.parseInt(userId)); // 调用 UserDao 的方法
    }

    public List<User> findUsersByCondition(UserConditionDto userCond){
        // 根据查询条件查找用户
        return userDao.selectUsersByCondition(userCond);
    }

    public void addUser(UserDto userDto){
        // 将 UserDto 转换为 User 对象
        User user = new User()
                .setName(userDto.getUsername())
                .setPassword(userDto.getPassword())  // 密码应加密
                .setGender(Integer.parseInt(userDto.getGender()))
                .setEmail(userDto.getEmail())
                .setStatus(Integer.parseInt(userDto.getStatus()))
                .setSalt(userDto.getUsername())
                .setCreateTime(new Date());

        // 调用 DAO 层的新增方法
        userDao.insert(user);
    }
    // 修改用户密码方法
    public boolean changeUserPassword(String userId, String newPassword){
        // 获取用户信息（例如，通过 userId 查询用户名，这里假设有 getUserById 方法）
        User user = userDao.getUserById(userId);  // 获取用户信息

        if (user == null) {
            // 如果用户不存在，返回 false 表示失败
            return false;
        }

        String username = user.getName();
        // 使用用户名作为 salt，加密新密码
        String encryptedPassword = StringUtils.md5Encoder(newPassword, username);

        // 调用 DAO 层的更新方法
        int rowsAffected = userDao.updateUserPassword(userId, encryptedPassword);

        // 判断是否修改成功
        return rowsAffected > 0;
    }

    @Override
    public void changePassword(String userId, String newPassword) {
        userDao.updateUserPassword(userId, newPassword);
    }
}
